package net.gazhi.delonix.weixin.mp.gson;

import java.io.IOException;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

/**
 * 用数字表示的 Boolean 类型转换适配器
 * 
 * @author Jeffrey Lin
 *
 */
public class NumericalBooleanAdapter extends TypeAdapter<Boolean> {

	@Override
	public void write(JsonWriter out, Boolean value) throws IOException {
		if (value == null) {
			out.nullValue();
			return;
		}
		out.value(value ? 1 : 0);
	}

	@Override
	public Boolean read(JsonReader in) throws IOException {
		if (in.peek() == JsonToken.NULL) {
			in.nextNull();
			return null;
		} else if (in.peek() == JsonToken.NUMBER) {
			return in.nextInt() == 0 ? false : true;
		}
		return in.nextBoolean();
	}

}
